/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao.Item;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import pojo.Item;
import util.SplitStringToNumberArray;

/**
 *
 * @author lg
 */
public class ItemDaoImpl implements ItemDao{
    private final Collection<Item> itens;
    
    public ItemDaoImpl(){
        this.itens = new ArrayList<>();
    }
    
    @Override
    public boolean salvar(Item item) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("smConfeccoesPU");
        EntityManager em = emf.createEntityManager ();
        try{
            em.getTransaction().begin();
            em.persist(item);
            em.getTransaction().commit();
            em.close();
            emf.close();
        }catch (RuntimeException e) {
            return false;
        }
        return true;
    }

    @Override
    public Collection<Item> listar() {   
        return this.itens;
    }

    @Override
    public boolean remover(Item item) {   
        return false;
    }
    
    @Override
    //falta terminar a copia dos atributos.
    //Só copiei os que precisava
    public void copiarObj(Item nomeObj) {
        for (Item iteratorItens : itens) {
            if (nomeObj.getNome().equals(iteratorItens.getNome())) {
                nomeObj.setId(iteratorItens.getId());
                nomeObj.setMargemLucro(iteratorItens.getMargemLucro());
                nomeObj.setPrecoCusto(iteratorItens.getPrecoCusto());
            }
        }
    }
    
    @Override
    public Item buscarPorNome(Item nomeObj){
        for (Item iteratorItens : itens) {
            if (nomeObj.getNome().equals(iteratorItens.getNome())) {
                return iteratorItens;
            }
        }
        return nomeObj;
    }
    
    @Override
    public Item buscarPorId(Item item) {
        Item itemTemp;
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("smConfeccoesPU");
        EntityManager em = emf.createEntityManager ();
        try{
            em.getTransaction().begin();
            itemTemp = em.find(item.getClass(),item.getId());
            em.getTransaction().commit();
            em.close();
            emf.close();
        }catch (IllegalArgumentException e) {
            return null;
        }
        return itemTemp;
    }

    @Override
    public boolean salvarDisco() {
        if(itens == null) return false;
        try {
            FileWriter writer = new FileWriter("registroItens");
            PrintWriter saida = new PrintWriter(writer);
            for (Item itensIterator : itens) {
                saida.println(itensIterator.getNome());
                saida.println(itensIterator.getId());
                saida.println(itensIterator.getMargemLucro());
                saida.println(itensIterator.getQuantidade());
                saida.println(itensIterator.getPrecoCusto());
                for (long iteratorItens : itensIterator.getFornecedores()) {
                    saida.print(iteratorItens);
                    saida.print('#');
                }
                saida.println();
                if (itensIterator.getPedidos().isEmpty()) {
                    saida.print("#");
                } else {
                    for (long iteratorItens : itensIterator.getPedidos()) {
                        saida.print(iteratorItens);
                        saida.print('#');
                    }
                }
                saida.println("\n");
            }
            writer.close();
            saida.close();
        } catch (IOException e) {
            System.out.println(e.toString());
            return false;
        }
        return true;
    }

    @Override
    public boolean carregarDisco() {
        Item item;
        String fornecedores;
        String pedidos;
        File arquivo = new File("registroItens");
        if(!arquivo.exists()) return false;
        FileReader reader;
        BufferedReader leitor;
        try {
            reader = new FileReader(arquivo);
            leitor = new BufferedReader(reader);
            while(leitor.ready()){
                item = new Item();
                item.setNome(leitor.readLine());
                item.setId(Long.parseLong(leitor.readLine()));
                item.setMargemLucro(Float.parseFloat(leitor.readLine()));
                item.setQuantidade(Integer.parseInt(leitor.readLine()));
                item.setPrecoCusto(Float.parseFloat(leitor.readLine()));
                fornecedores = leitor.readLine();               
                item.setFornecedores(SplitStringToNumberArray.convertLong(fornecedores));
                pedidos = leitor.readLine();
                item.setPedidos(SplitStringToNumberArray.convertLong(pedidos));
                this.salvar(item);
                leitor.readLine();
            }
            reader.close();
            leitor.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ItemDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {            
            Logger.getLogger(ItemDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }  
}
